function extract_info() {
    var info = DOUBAN.parse_url(location.href);

    info.name = $('h1').text();

    return info;
}

var info = null;

function show_import_button() {
    DOUBAN.update_button('import', '导入').click(function () {
        read_option('douban_access_token', function (key, value) {
            if (value) {
                show_or_load_doulist();
            } else {
                chrome.extension.sendRequest({
                    action: 'oauth'
                }, function (response) {
                    if (response.access_token) {
                        show_or_load_doulist();
                    }
                });
            }
        });

        return false;
    });
}

function show_or_load_doulist() {
    if (info) {
        show_import_dialog(false);
    }
    else {
        DOUBAN.show_dialog("<div id='importing' class='loadpop'>正在加载豆列，请稍候...</div>");

        chrome.extension.sendRequest({
            action: 'load',
            info: extract_info()
        }, function (response) {
            console.log(response);

            info = response.info;

            show_import_dialog(true);
        });
    }
}

function connect_handler(port) {
    if (port.name == 'importing') {
        port.onMessage.addListener(function(info) {
            console.log(info);

            $('#importing_items').append("<div>" +
                "<a href='" + info.url + "' target='_blank'>" +
                    "<img src='" + info.poster + "' alt='" + info.name + "'></a></div>");

            var api = $(".scrollable").data("scrollable");
            api.addItem($("#importing_items div")).end();

            DOUBAN.refine_dialog();
        });
    }
}

function import_doulist() {
    info.rating = parseInt($('#n_rating').val());
    info.tags = ($('#tags').val() || '').split(' ');
    info.status = $('input:radio.status:checked').val();
    info.content = $('#comment').val();
    info.private = $('#inp-private:checked').length > 0;

    $('#importing').html(
        "<div id='importing' class='loadpop'>正在导入豆列，请稍候...<br/><br/>" +
            "<div class='scrollable' style='background:url(" + chrome.extension.getURL('/assets/img/h300.png') + ") repeat-x;'>" +
                "<div class='items'></div></div>" +
            "<div id='importing_items' style='display: none'></div>");

    $('.scrollable').scrollable({ mousewheel: true });
    
    DOUBAN.refine_dialog();

    chrome.extension.onConnect.addListener(connect_handler);

    chrome.extension.sendRequest({
        action: 'import',
        info: info
    }, function (response) {
        console.log(response);

        chrome.extension.onConnect.removeListener(connect_handler);

        DOUBAN.close_dialog();
    });
}

var no_star_img_url = chrome.extension.getURL('/assets/img/nst.gif');
var star_img_url = chrome.extension.getURL('/assets/img/st.gif');
var star_highlight_img_url = chrome.extension.getURL('/assets/img/sth.gif');

function show_import_dialog(update) {
    if (info.category == 'movie') {
        buttons = {
            wish: '想看',
            watched: '看过'
        }
    } else if (info.category == 'book') {
        buttons = {
            wish: '想读',
            reading: '在读',
            read: '读过'
        }
    } else if (info.category == 'book') {
        buttons = {
            wish: '想听',
            listening: '在听',
            listened: '听过'
        }
    }

    var html = "";

    for (var status in buttons) {
        html += "<input type='radio' class='status' name='status' id='status_" + status + "' value='" + status + "'>" +
                "<label for='status_" + status + "'>" + buttons[status] + "&nbsp;&nbsp;</label>";
    }

    html = "<div id='importing' class='indentpop1 clearfix'>" +
    "<form class='j a_interest_form'>" +
        "<div class='interest-form-hd'>" +
            "<span class='gact rr'><a href='javascript:void(0);' onclick='DOUBAN.close_dialog()'>x</a></span>" +
            "<h2>添加收藏：导入豆列&nbsp;<i>" + info.name + "</i>&nbsp;中的" + info.items.length + "个项目</h2>" +
        "</div>" +
        "<div class='tags-switch'>" +
            "<a id='showtags' rel='高级(标签和附注) ▼' href='javascript:void(0)'>缩起 ▲</a>" +
        "</div>" +
        "<ul id='advtags' class='interest_form'>" +
            "<li>标签(多个标签用空格分隔):</li>" +
            "<li><input id='tags' type='text' class='inp-tags'></li>" +
            "<li class='comment-label'><span id='left_n' class='num'>350</span>简短附注:</li>" +
            "<li><textarea name='comment' class='comment' id='comment' maxlength='350'></textarea></li>" +
            "<li>" + html + "</li>" +
            "<div class='interest-rating' style='display: none'>" +
                "<span class='j a_stars'><p class='rate_stars'>给个评价吧?(可选):" +
                    "<span id='rating'>" +
                        "<span id='stars'>" +
                            "<img src='" + no_star_img_url + "' id='star1'>" +
                            "<img src='" + no_star_img_url + "' id='star2'>" +
                            "<img src='" + no_star_img_url + "' id='star3'>" +
                            "<img src='" + no_star_img_url + "' id='star4'>" +
                            "<img src='" + no_star_img_url + "' id='star5'>" +
                        "</span>" +
                        "<span id='rateword' class='pl'></span>" +
                    "</span>" +
                        "<input id='n_rating' type='hidden' value='' name='rating'></p>" +
                "</span>" +
            "</div>" +
            "<li class='private'>" +
                "<label class='pl' for='inp-private'>" +
                "<input id='inp-private' name='private' type='checkbox'>仅自己可见</label>" +
            "</li>" +
        "</ul>" +
        "<div class='interest-form-ft recsubmit' id='submits'>" +
            "<label class='pl shuo' for='inp-broadcast'>" +
            "<input id='inp-broadcast' name='broadcast' type='checkbox' checked='checked'>收藏后写一条我说</label>&nbsp;" +
            "<span class='bn-flat'><input value='取消' type='button' onclick='DOUBAN.close_dialog()'></span>" +
            "<span class='bn-flat'><input value='导入' type='button' id='import_doulist'></span>" +
        "</div>" +
    "</form></div>";

    if (update) {
        $('#importing').html(html).removeAttr('class');
    } else {
        DOUBAN.show_dialog(html);
    }

    $('.status').change(function () {
        $('.interest-rating').toggle($(this).val() != 'wish');
    })
    $('#status_wish').attr('checked', 'checked');
    $('#import_doulist').click(import_doulist);

    var stars = $('#stars img');

    stars.each(function (idx, star) {
        $(star).hover(function () {
            var num = parseInt($(this).attr('id').charAt(4));

            for (var i=1; i<=num; i++) {
                $(stars[i-1]).attr('src', star_highlight_img_url);
            }

            var ratewords = ['很差', '较差', '还行', '推荐', '力荐'];

            $('#rateword').text(ratewords[num-1]);
        }, function () {
            refresh_stars();

            $('#rateword').text('');
        }).click(function () {
            var num = parseInt($(this).attr('id').charAt(4));

            $('#n_rating').val(num);

            refresh_stars();
        });
    });

    $('#showtags').click(function () {
        var text = $(this).attr('rel');
        $(this).attr('rel', $(this).text());
        $(this).text(text);
        $('#advtags').toggle();

        DOUBAN.refine_dialog();
    })

    $('#comment').keyup(function () {
        $('#left_n').text(350-$(this).val().length);
    });

    DOUBAN.refine_dialog();
}

function refresh_stars() {
    var stars = $('#stars img');
    var rating = parseInt($('#n_rating').val());

    for (var i=1; i<=5; i++) {
        if (i <= rating) {
            $(stars[i-1]).attr('src', star_img_url);
        } else {
            $(stars[i-1]).attr('src', no_star_img_url);
        }
    }
}

read_option('doulist_import', function (key, value) {
    if (value) {
        show_import_button();
    }
});
